<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
            <el-form-item label="故障代码" prop="faultCode">
                <el-input v-model="queryParams.faultCode" placeholder="请输入故障代码" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="故障参数名" prop="faultName">
                <el-input v-model="queryParams.faultName" placeholder="请输入故障参数名" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="创建时间">
                <el-date-picker v-model="dateRange" style="width: 340px" value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetimerange" range-separator="-" start-placeholder="开始日期"
                    end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['system:role:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" @click="handleImport"
                    v-hasPermi="['system:role:edit']">批量导入</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleDownload"
                    v-hasPermi="['system:role:export']">下载模版</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 添加或修改用户配置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="故障代码" prop="faultCode">
                            <el-input v-model="form.faultCode" placeholder="请输入故障代码" maxlength="30" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="故障参数名" prop="faultName">
                            <el-select v-model="form.faultName" placeholder="请选择故障参数" :disabled="this.title == '修改故障信息配置'">
                                <el-option v-for="item in faultNameList" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="故障说明" prop="faultDescription">
                            <el-input type="textarea" v-model="form.faultDescription" placeholder="请输入故障说明"
                                maxlength="11" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="故障标识" prop="faultIdentification">
                            <el-select v-model="form.faultIdentification" placeholder="请选择故障标识" style="width: 100%;">
                                <el-option v-for="item in options" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input v-model="form.notes" type="textarea" placeholder="请输入内容"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <el-table v-loading="loading" :data="deviceList">
            <!-- <el-table-column type="selection" width="55" align="center" /> -->
            <el-table-column label="序号" type="index" width="50" />
            <el-table-column label="故障代码" prop="faultCode" :show-overflow-tooltip="true" width="auto" />
            <el-table-column label="故障参数名" prop="faultName" :show-overflow-tooltip="true" width="auto" />
            <el-table-column label="故障说明" prop="faultDescription" width="200" />
            <el-table-column label="故障标识" prop="faultIdentification" :show-overflow-tooltip="true" width="auto">
                <template slot-scope="scope">
                    <span>{{ scope.row.faultIdentification == 0 ? '否':(scope.row.faultIdentification == 1?'是':'')}}</span>
                </template>
            </el-table-column>

            <el-table-column label="创建时间" prop="faultCreateTime" :show-overflow-tooltip="true" width="auto">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.faultCreateTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="更新时间" prop="faultUpdateTime" :show-overflow-tooltip="true" width="auto">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.faultCreateTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['system:role:edit']">编辑</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['system:role:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                name="multipartFile" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
                :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <span>仅允许导入xls、xlsx格式文件。</span>

                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />
    </div>
</template>

<script>
    import { getList, save, downloadTemplate, deleteFault, batchSave, getDetail, getFaultAll } from "@/api/device/index";
    import moment from 'moment'
    import { getToken } from '@/utils/auth'
    import { downloadXls } from '@/utils/ruoyi'


    export default {
        name: "Role",
        // dicts: ['alarm_type'],
        data() {
            return {
                // 遮罩层
                loading: true,
                // 选中数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                // 角色表格数据
                deviceList: [],
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                // 是否显示弹出层（数据权限）
                openDataScope: false,
                menuExpand: false,
                menuNodeAll: false,
                deptExpand: true,
                deptNodeAll: false,
                // 日期范围
                dateRange: ['', ''],
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10
                },
                // 表单参数
                form: {},
                // 导入参数
                upload: {
                    // 是否显示弹出层（用户导入）
                    open: false,
                    // 弹出层标题（用户导入）
                    title: "",
                    // 是否禁用上传
                    isUploading: false,
                    // 是否更新已经存在的用户数据
                    updateSupport: 0,
                    // 设置上传的请求头部
                    headers: { Authorization: "Bearer " + getToken() },
                    // 上传的地址
                    url: process.env.VUE_APP_BASE_API + "/fault/information/batchSave"
                },
                options: [
                    {
                        label: '是',
                        value: 1
                    }, {
                        label: '否',
                        value: 0
                    }],
                rules: {
                    faultCode: [
                        { required: true, message: "故障代码不能为空", trigger: "blur" }
                    ],
                    faultName: [
                        { required: true, message: "故障参数名不能为空", trigger: "blur" }
                    ],
                    faultIdentification: [
                        { required: true, message: "故障标识不能为空", trigger: "blur" }
                    ]
                },
                faultNameList: []
            };
        },
        created() {
            let startTime = moment().subtract(1, 'month').format('YYYY-MM-DD') + ' 00:00:00';
            let endTime = this.parseTime(new Date());
            this.dateRange = [startTime, endTime]
            this.getList();
            this.getFaultName();
        },
        methods: {
            /** 查询设备状态列表 */
            getList() {
                this.loading = true;
                getList(this.addDateTimeRange(this.queryParams, this.dateRange)).then(response => {
                    this.deviceList = response.rows;
                    this.total = response.total;
                    this.loading = false;
                });
            },
            getFaultName() {
                getFaultAll().then(res => {
                    for (const key in res.data) {
                        this.faultNameList.push({
                            value: res.data[key],
                            name: key
                        })
                    }
                })
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 取消按钮（数据权限）
            cancelDataScope() {
                this.openDataScope = false;
                this.reset();
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.dateRange = [];
                this.resetForm("queryForm");
                this.handleQuery();
            },
            // 多选框选中数据
            handleSelectionChange(selection) {
                this.ids = selection.map(item => item.roleId)
                this.single = selection.length != 1
                this.multiple = !selection.length
            },
            /** 新增按钮操作 */
            handleAdd() {
                this.reset();
                this.open = true;
                this.title = "新增故障信息配置";
            },
            handleDownload() {
                downloadTemplate().then(res => {
                    downloadXls(res, '故障信息配置模板.xlsx')
                }).catch(error => {
                    this.$message.error("下载模版出错")
                })
            },
            handleImport() {
                this.upload.title = "批量导入";
                this.upload.open = true;
            },
            reset() {
                this.form = {
                    id: undefined,
                    faultCode: undefined,
                    faultDescription: undefined,
                    faultIdentification: undefined,
                    faultName: undefined,
                    notes: undefined,
                };
                this.resetForm("form");
            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                this.reset();
                const id = row.id
                getDetail({ id: id }).then(response => {
                    this.form = response.data;
                    this.open = true;
                    this.title = "修改故障信息配置";
                });
            },

            /** 提交按钮 */
            submitForm: function () {
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        if (this.form.id != undefined) {
                            save(this.form).then(response => {
                                this.$modal.msgSuccess("修改成功");
                                this.open = false;
                                this.getList();
                            });
                        } else {

                            save(this.form).then(response => {
                                this.$modal.msgSuccess("新增成功");
                                this.open = false;
                                this.getList();
                            });
                        }
                    }
                });
            },
            /** 提交按钮（数据权限） */
            submitDataScope: function () {
                if (this.form.roleId != undefined) {
                    this.form.deptIds = this.getDeptAllCheckedKeys();
                    dataScope(this.form).then(response => {
                        this.$modal.msgSuccess("修改成功");
                        this.openDataScope = false;
                        this.getList();
                    });
                }
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                const id = [row.id]
                this.$modal.confirm('确定删除选中的故障信息配置数据吗？').then(function () {
                    return deleteFault(id);
                }).then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                }).catch(() => { });
            },
            // 文件上传中处理
            handleFileUploadProgress(event, file, fileList) {
                this.upload.isUploading = true;
            },
            // 文件上传成功处理
            handleFileSuccess(response, file, fileList) {
                this.upload.open = false;
                this.upload.isUploading = false;
                this.$refs.upload.clearFiles();
                this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
                this.getList();
            },
            // 提交上传文件
            submitFileForm() {
                this.$refs.upload.submit();
            }
        }
    };
</script>
